<?php

namespace SC\Admin\Widgets\Support;

use Closure;


class Field
{
    protected $type = null;
    protected $name = null;
    protected $label = null;
    protected $as = null;
    protected $required = false;
    protected $disabled = false;

    public function __construct($name, $label=null)
    {
        $this->name = $name;
        $this->label = $label ?: \str_replace(['.', '_'], ' ', \ucfirst($name));
    }

    public function type($type)
    {
        $this->type = $type;
        return $this;
    }

    public function label($label)
    {
        $this->label = $label;
        return $this;
    }

    public function as(Closure $as)
    {
        $this->as = $as;
        return $this;
    }

    public function required($required=true)
    {
        $this->required = $required;
        return $this;
    }

    public function disabled($disabled=true)
    {
        $this->disabled = $disabled;
        return $this;
    }

    public function isPure()
    {
        return \is_null($this->as);
    }

    public function meta()
    {
        return [
            'name' => $this->name,
            'label' => $this->label,
            'type' => $this->type,
            'required' => $this->required,
            'disabled' => $this->disabled,
            'isPure' => $this->isPure(),
        ];
    }

    public function value($inst)
    {
        if ($this->isPure()) {
            $value = $inst;
            foreach (\explode('.', $this->name) as $attr) {
                if (\is_null($value)) {
                    break;
                }
                $value = $value->{$attr};
            }
            return $value;
        } else {
            return $this->as->bindTo($inst)();
        }
    }
}